/*
 * @Author: DUST
 * @Date: 2023-11-26 11:16:37
 * @LastEditors: DUST
 * @LastEditTime: 2024-01-20 11:24:59
 * @FilePath: \business-card-system\server\app\controller\CompanyController.ts
 * @Description:
 * undefined
 */
import { Context } from "koa";
import CompanyServeice from "../service/CompanyService";
import responese from "../../utils/responese";
import CompanyValidator, { CompanyItem } from "../validator/CompanyValidator";
import validate from "../../utils/validator";
import fs from "fs";
import path from "path";
import MD5 from "../../utils/MD5";

class CompanyController {
  /**
   * @description: 获取笔记列表
   * @param {Context} ctx：请求体
   */
  async getAppCompanyInfo(ctx: Context) {
    const companyInfo = await CompanyServeice.getCompanyInfo();

    if (companyInfo === null) return responese.success(ctx, {});
    // console.log(companyInfo);
    if (companyInfo.imgs) {
      companyInfo.imgs = JSON.parse(companyInfo.imgs);
    }
    if (companyInfo.swippers) {
      companyInfo.swippers = JSON.parse(companyInfo.swippers);
    }
    responese.success(ctx, companyInfo);
  }
  /**
   * @description: 获取两个公司地址
   * @param {Context} ctx：请求体
   */
  async getCompanyAddrList(ctx: Context) {
    const params = ctx.params;
    console.log(params);
    if (isNaN(params.unitId))
      return responese.errorResponese(ctx, "参数错误！");

    const companyInfo = await CompanyServeice.getCompanyAddr(params.unitId);

    if (companyInfo === null) return responese.success(ctx, {});
    console.log(companyInfo);
    
    // console.log("轮播图片信息：", companyInfo.swippers);
    responese.success(ctx, companyInfo);
  }
  /**
   * @description: 获取笔记列表
   * @param {Context} ctx：请求体
   */
  async getCompanyInfo(ctx: Context) {
    const params = ctx.params;
    console.log(params);
    if (isNaN(params.unitId))
      return responese.errorResponese(ctx, "参数错误！");

    const companyInfo = await CompanyServeice.getCompanyByUnitId(params.unitId);

    if (companyInfo === null) return responese.success(ctx, {});
    // console.log(companyInfo);
    if (companyInfo.imgs) {
      companyInfo.imgs = JSON.parse(companyInfo.imgs);
    }
    if (companyInfo.swippers) {
      companyInfo.swippers = JSON.parse(companyInfo.swippers);
    }
    
    // console.log("轮播图片信息：", companyInfo.swippers);
    responese.success(ctx, companyInfo);
  }

  public addCompany = async (ctx: Context) => {
    const filePath = this.uploadFile(ctx);
    const swipperPaths = this.uploadsSwipperFile(ctx);
    const videoPath = this.uploadVideo(ctx, true);
    console.log("filePath", filePath);
    const { data, msg } = await validate(ctx, CompanyValidator.addRules);
    if (msg != null) return responese.errorResponese(ctx, msg);
    if (filePath && filePath.length) {
      // filePath.forEach((url: string) => {
      //   data.imgs += url + ","
      // })
      data.imgs = JSON.stringify(filePath);
    }
    if (swipperPaths && swipperPaths.length) {
      data.swippers = JSON.stringify(swipperPaths);
    }
    if (videoPath) data.video = videoPath;
    console.log(data);
    const rows = await CompanyServeice.addCompany(data);
    if (rows?.id) return responese.success(ctx, null);

    responese.errorResponese(ctx, "新增失败");
  };

  public editCompany = async (ctx: Context) => {
    const filePath = this.uploadFile(ctx, true);
    const swipperPaths = this.uploadsSwipperFile(ctx, true);
    const videoPath = this.uploadVideo(ctx, true);
    console.log("file", filePath);
    const {
      data: {
        name,
        desName,
        desName1,
        desName3,
        video,
        addr,
        addr2,
        lng,
        lat,
        imgs,
        swippers,
        unitId,
        id,
      },
      msg,
    } = await validate<CompanyItem & { id: number }>(
      ctx,
      CompanyValidator.editRules
    );
    if (msg) return responese.errorResponese(ctx, msg);
    if (isNaN(id)) return responese.errorResponese(ctx, "传入ID参数类型错误");
    console.log("JSON.stringify([...imgs, ...filePath])：", swipperPaths, swippers);
    const row = await CompanyServeice.editCompany(
      {
        name,
        desName,
        desName1,
        desName3,
        addr,
        addr2,
        lng,
        lat,
        video: videoPath || video || null,
        imgs: filePath
          ? JSON.stringify([...JSON.parse(imgs), ...filePath])
          : imgs,
        swippers: swipperPaths
          ? (swippers ? JSON.stringify([...JSON.parse(swippers), ...swipperPaths]) : JSON.stringify([...swipperPaths]))
          : (swippers || JSON.stringify([])),
        unitId,
      },
      id
    );
    console.log("编辑：", row);
    if (row) return responese.success(ctx, null, "编辑成功");
    responese.errorResponese(ctx, "编辑失败");
  };

  uploadFile = (ctx: Context, isCanBeNull = false): string[] | false | any => {
    console.log("开始文件存储~", ctx.request.files);
    const file = ctx.request.files?.files;
    if (file) {
      if (Object.prototype.toString.call(file) == "[object Array]") {
        const filePathArr: string[] = [];
        // @ts-ignore
        for (let i = 0; i < file.length; i++) {
          const element = file[i];
          filePathArr.push(this.storageFile(element));
        }
        return filePathArr;
        // @ts-ignore
      } else return [this.storageFile(file)];
    } else if (isCanBeNull) {
      return false;
    } else {
      return responese.errorResponese(ctx, "文件缺失");
    }
  };

  uploadsSwipperFile = (
    ctx: Context,
    isCanBeNull = false
  ): string[] | false | any => {
    console.log("开始文件存储~", ctx.request.files);
    const file = ctx.request.files?.swipperFiles;
    if (file) {
      if (Object.prototype.toString.call(file) == "[object Array]") {
        const filePathArr: string[] = [];
        // @ts-ignore
        for (let i = 0; i < file.length; i++) {
          const element = file[i];
          filePathArr.push(this.storageFile(element));
        }
        return filePathArr;
        // @ts-ignore
      } else return [this.storageFile(file)];
    } else if (isCanBeNull) {
      return false;
    } else {
      return responese.errorResponese(ctx, "文件缺失");
    }
  };
  uploadVideo = (ctx: Context, isCanBeNull = false): string[] | false | any => {
    console.log("开始视频存储~", ctx.request.files);
    const video = ctx.request.files?.video;
    if (video) {
      return this.storageFile(video as unknown as File);
    } else if (isCanBeNull) {
      return false;
    } else {
      return responese.errorResponese(ctx, "视频文件缺失");
    }
  };
  createStr = () => {
    const date = Number(new Date());
    return MD5(date.toString());
  };
  storageFile = (file: File) => {
    // @ts-ignore
    const type = file.mimetype;
    //@ts-ignore
    const name = file.originalFilename;
    console.log(file, type, name);
    //@ts-ignore
    const fileStream = fs.createReadStream(file.filepath);
    const ext = path.extname(name);
    const filePath = "/upload/" + this.createStr() + ext;
    const writeFile = fs.createWriteStream("public" + filePath);
    fileStream.pipe(writeFile);
    return filePath;
  };
}

export default new CompanyController();
